package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired(required = false)
    private EmployeeMapper employeeMapper;
    @Override
    public R<Employee> login(Employee employee) {
        Employee dbEmployee = employeeMapper.login(employee);
        if(dbEmployee==null){
            return R.error("用户登入失败");
        }
        if(!dbEmployee.getPassword().equals(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes()))){
            return R.error("密码错误！");
        }
        if(dbEmployee.getStatus()==0){
            return R.error("用户被禁用！");
        }
        return R.success(dbEmployee);
    }

    @Override
    public void save(Employee employee) {
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employeeMapper.save(employee);
    }
    //分页
    @Override
    public Page<Employee> findByName(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page,pageSize);

        List<Employee> employeeList = employeeMapper.findByName(name);

        PageInfo<Employee> pageInfo = new PageInfo<>(employeeList);

        Page<Employee> employeePage = new Page<Employee>(pageInfo.getList(), pageInfo.getTotal(), pageInfo.getPageNum(), pageInfo.getPageSize());

        return employeePage;
    }

    @Override
    public void update(Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        employeeMapper.update(employee);
    }

    @Override
    public R<Employee> findById(Integer id) {
        Employee employee=employeeMapper.findById(id);

        return R.success(employee);
    }

    //修改禁用的状态

}
